package tools.tinyXML;

import java.io.BufferedReader;
import java.io.IOException;

public class tinyXmlParser {

		private BufferedReader reader;
		private boolean hasmore= false;
		String s=null;
		private tinyXmlUnit curUnit=null;
		private tinyXmlUnit nextUnit=null;
		
		/**
		 * 
		 * @param reader
		 * @throws IOException
		 * @throws BioException
		 */
		
		//big time fulhack
		public tinyXmlParser(BufferedReader reader) throws IOException, Exception{
			this.reader= reader;
			
			readNext();
		}
		
		public tinyXmlUnit next() throws IOException, Exception{
			if (!hasmore) {
				throw new Exception("No more hits 1");
			}
			curUnit= nextUnit;
			readNext();
			return curUnit;
		}
		
		public boolean hasNext() {
			return hasmore;
		}
		
		
		private void readNext() throws IOException, Exception{
			nextUnit= new tinyXmlUnit();
			for(s=reader.readLine();s!=null;s=reader.readLine()){
				s=s.trim();
				if(s.startsWith("<TSeq>")){
					break;
				}
			}
			if (s==null) {
				hasmore= false;
			}else {
				for(s=reader.readLine().trim();!s.startsWith("</TSeq>");s=reader.readLine().trim()){
					if(s.startsWith("<TSeq_seqtype")){
						nextUnit.setSeqtype(s.split("\"")[1]);
					}else if(s.startsWith("<TSeq_gi")){
						nextUnit.setGi(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}else if(s.startsWith("<TSeq_accver")){
						nextUnit.setAccver(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}else if(s.startsWith("<TSeq_taxid")){
						nextUnit.setTaxid(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}else if(s.startsWith("<TSeq_orgname")){
						nextUnit.setOrgname(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}else if(s.startsWith("<TSeq_defline")){
						nextUnit.setDefline(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}else if(s.startsWith("<TSeq_length")){
						nextUnit.setLength(Integer.parseInt(s.substring(s.indexOf('>')+1, s.lastIndexOf('<'))));
					}else if(s.startsWith("<TSeq_sequence")){
						nextUnit.setSeq(s.substring(s.indexOf('>')+1, s.lastIndexOf('<')));
					}
				}
				hasmore=true;
			}
		}
}
